﻿using UnityEngine;
using UnityEditor;
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using Object = UnityEngine.Object;

public class ChangeFontsWindow : EditorWindow 
{      
	[MenuItem ("Tools/UIFont/Change Fonts")]    
	static void Init () 
	{           
		ChangeFontsWindow window = (ChangeFontsWindow)EditorWindow.GetWindow (typeof(ChangeFontsWindow));   
	}        
	
	static Dictionary<UIFont, UIFont> changeList = new Dictionary<UIFont, UIFont>();	//要更换的列表
	static UIFont tempSourceFont;
	static UIFont tempTargetFont;
	
	static bool readyToAdd = false;
	void OnGUI () 
	{        
		if(GUILayout.Button("Add a change item"))
		{
			readyToAdd = true;
		}
		
		if(readyToAdd)
		{
			EditorGUILayout.BeginHorizontal();
			{				
				tempSourceFont = EditorGUILayout.ObjectField("SourceFont", tempSourceFont, typeof(UIFont), true) as UIFont;
				tempTargetFont = EditorGUILayout.ObjectField("TargetFont", tempTargetFont, typeof(UIFont), true) as UIFont;
				
				if(GUILayout.Button("Add"))			
					AddChange();
			}
			EditorGUILayout.EndHorizontal();
		}
		
		
		if(changeList.Count > 0)
		{
			EditorGUILayout.LabelField("-----------------------更换列表-----------------------");
			foreach(UIFont tempSourceFont in changeList.Keys)
			{
				EditorGUILayout.BeginHorizontal();
				{
					EditorGUILayout.ObjectField("SourceFont", tempSourceFont, typeof(UIFont), false);
					EditorGUILayout.LabelField("------>");
					EditorGUILayout.ObjectField("TargetFont", changeList[tempSourceFont], typeof(UIFont), false);
				}
				EditorGUILayout.EndHorizontal();
			}
			
			EditorGUILayout.BeginHorizontal();
			{
				if(GUILayout.Button("Change Now"))
					StartChange();
				if(GUILayout.Button("Clean List"))
					changeList.Clear();
			}
			EditorGUILayout.EndHorizontal();
		}
	}
	
	static void AddChange()
	{		
		if(tempSourceFont == null || tempTargetFont == null)	
		{
			Debug.LogWarning("请选择需要替换的前后字体！");
			return;
		}
		
		changeList.Add(tempSourceFont, tempTargetFont);
		readyToAdd = false;
	}
	
	static void StartChange()
	{				
		UIChangedList.Clean();
		
		foreach(UIFont oldFont in changeList.Keys)
		{
			UpdateFont(oldFont, changeList[oldFont]);
		}		
		
		UIChangedList.Save();
	}
	
	/// <summary>
	/// 更新引用者的资源
	/// oldFont:原字库
	/// newFont:新字库
	/// </summary>
	public static void UpdateFont(UIFont oldFont, UIFont newFont)
	{
		char[] trimEnd = (".prefab").ToCharArray();
		string fontPath = AssetDatabase.GetAssetPath(oldFont).TrimEnd(trimEnd);
		Debug.Log(string.Format("开始同步[{0}]的引用:......", fontPath));
		
		string fileFolder = "Assets/GameResources/UI/Dep/";
	 	string[] files = Directory.GetFiles(fileFolder, "*", SearchOption.AllDirectories);
        foreach(string file in files)
        {			
			if(file.Contains(".meta"))
				continue;
			
			Object obj = AssetDatabase.LoadMainAssetAtPath(file);
			
			if(obj is GameObject)
			{
				GameObject gameObj = obj as GameObject;
				UpdateObjDep(file.TrimEnd(trimEnd), gameObj.transform, oldFont, newFont, false, file);
			}
		}
		
		Debug.Log("同步结束！");
	}
		
	/// <summary>
	/// 更新引用者的资源
	/// objPath:引用者路径
	/// trans:引用者
	/// oldFont:原字库
	/// newFont:新字库
	/// </summary>
	static void UpdateObjDep(string objPath, Transform trans, UIFont oldFont, UIFont newFont, bool record, string file)
	{
		bool hasDep = false;
		
		UILabel label = trans.GetComponent<UILabel>();
		if(label != null)
		{
			if(label.font == oldFont)
			{
				label.font = newFont;
				label.MakePixelPerfect();
				hasDep = true;
			}
		}
		
//		UIMix mix = trans.GetComponent<UIMix>();
//		if(mix != null)
//		{
//			if(mix.defaultFont == oldFont)
//			{
//				mix.defaultFont = newFont;
//				hasDep = true;
//			}
//			
//			for(int i = 0; i < mix.fontList.Count; i++)
//			{
//				if(mix.fontList[i] == oldFont)
//				{
//					mix.fontList[i] = newFont;
//					hasDep = true;
//				}
//			}
//		}
		
		if(hasDep)
		{
			if(!record)
			{
				record = true;
				UIChangedList.Add(file);
			}
			Debug.Log(string.Format("已同步：{0}", objPath));
		}
		
		//子节点递归
		for(int j = 0; j < trans.childCount; j++)
		{
			Transform child = trans.GetChild(j);
			UpdateObjDep(objPath + "/" + child.name, child, oldFont, newFont, record, file);
		}
	}
	
	[MenuItem ("Tools/UIFont/Show Null Font")]  
	static void ShowNullFont()
	{
		char[] trimEnd = (".prefab").ToCharArray();
		Debug.Log("开始检测Null Font:......");
		
		string fileFolder = "Assets/GameResources/UI/Dep/";
	 	string[] files = Directory.GetFiles(fileFolder, "*", SearchOption.AllDirectories);
        foreach(string file in files)
        {			
			if(file.Contains(".meta"))
				continue;
			
			Object obj = AssetDatabase.LoadMainAssetAtPath(file);
			
			if(obj is GameObject)
			{
				GameObject gameObj = obj as GameObject;
				CheckNullFont(file.TrimEnd(trimEnd), gameObj.transform);
			}
		}
		
		Debug.Log("检测完毕！");
	}
	
	/// <summary>
	/// 检测空字库
	/// objPath:引用者路径
	/// trans:引用者
	/// </summary>
	static void CheckNullFont(string objPath, Transform trans)
	{
		bool hasNullFont = false;
		UILabel label = trans.GetComponent<UILabel>();
		if(label != null)
		{
			if(label.font == null)
			{
				hasNullFont = true;
			}
		}
		
//		UIMix mix = trans.GetComponent<UIMix>();
//		if(mix != null)
//		{
//			if(mix.defaultFont == null)
//			{
//				hasNullFont = true;
//			}
//		}
		
		UIPopupList pop = trans.GetComponent<UIPopupList>();
		if(pop != null)
		{
			if(pop.font == null)
			{
				hasNullFont = true;
			}
		}
		
		if(hasNullFont)
		{
			Debug.Log(string.Format("NULL Font：{0}", objPath));
		}
		
		//子节点递归
		for(int j = 0; j < trans.childCount; j++)
		{
			Transform child = trans.GetChild(j);
			CheckNullFont(objPath + "/" + child.name, child);
		}
	}
	
	static UIFont selectedFont;
	[MenuItem ("Tools/UIFont/Show Selected Font Dep")]  
	static void ShowSelectedFont()
	{
		if(Selection.activeGameObject != null)
			selectedFont = Selection.activeGameObject.GetComponent<UIFont>();
		if(selectedFont == null)
		{
			Debug.LogError("未选中图集！");
			return;
		}
		
		char[] trimEnd = (".prefab").ToCharArray();
		Debug.Log("开始检测Font Dep:......");
		
		string fileFolder = "Assets/GameResources/UI/Dep/";
	 	string[] files = Directory.GetFiles(fileFolder, "*", SearchOption.AllDirectories);
        foreach(string file in files)
        {			
			if(file.Contains(".meta"))
				continue;
			
			Object obj = AssetDatabase.LoadMainAssetAtPath(file);
			
			if(obj is GameObject)
			{
				GameObject gameObj = obj as GameObject;
				CheckSelectedFontDep(file.TrimEnd(trimEnd), gameObj.transform);
			}
		}
		
		Debug.Log("检测完毕！");
	}
	
	/// <summary>
	/// 检测字库引用
	/// objPath:引用者路径
	/// trans:引用者
	/// </summary>
	static void CheckSelectedFontDep(string objPath, Transform trans)
	{
		bool hasSelectedFont = false;
		UILabel label = trans.GetComponent<UILabel>();
		if(label != null)
		{
			if(label.font == selectedFont)
			{
				hasSelectedFont = true;
			}
		}
		
//		UIMix mix = trans.GetComponent<UIMix>();
//		if(mix != null)
//		{
//			if(mix.defaultFont == selectedFont)
//			{
//				hasSelectedFont = true;
//			}
//		}
		
		UIPopupList pop = trans.GetComponent<UIPopupList>();
		if(pop != null)
		{
			if(pop.font == selectedFont)
			{
				hasSelectedFont = true;
			}
		}
		
		if(hasSelectedFont)
		{
			Debug.Log(string.Format("Font Dep：{0}", objPath));
		}
		
		//子节点递归
		for(int j = 0; j < trans.childCount; j++)
		{
			Transform child = trans.GetChild(j);
			CheckSelectedFontDep(objPath + "/" + child.name, child);
		}
	}
	
	[MenuItem ("Tools/UIFont/Show Zoomed Labels")]  
	public static void CheckNotPerfectPixelLabels()
	{
		char[] trimEnd = (".prefab").ToCharArray();
		Debug.Log("开始检测Zoomed Labels:......");
		
		string fileFolder = "Assets/GameResources/UI/Dep/";
	 	string[] files = Directory.GetFiles(fileFolder, "*", SearchOption.AllDirectories);
        foreach(string file in files)
        {			
			if(file.Contains(".meta"))
				continue;
			
			Object obj = AssetDatabase.LoadMainAssetAtPath(file);
			
			if(obj is GameObject)
			{
				GameObject gameObj = obj as GameObject;
				CheckNotPerfectPixelLabel(file.TrimEnd(trimEnd), gameObj.transform);
			}
		}
		
		Debug.Log("检测完毕！");
	}
	
	/// <summary>
	/// 检测非完美像素Label
	/// objPath:引用者路径
	/// trans:引用者
	/// </summary>
	static void CheckNotPerfectPixelLabel(string objPath, Transform trans)
	{
		UILabel label = trans.GetComponent<UILabel>();
		if(label != null)
		{
			UIFont font = label.font;
			if(font != null)
			{
				float pixelSize = (font.atlas != null) ? font.atlas.pixelSize : 1f;
	
				Vector3 scale = label.cachedTransform.localScale;
				scale.x = font.size * pixelSize;
				scale.y = scale.x;
		
				if(label.cachedTransform.localScale != scale)
					Debug.Log(string.Format("Zoomed Label：{0}", objPath));
			}
		}
		
		//子节点递归
		for(int j = 0; j < trans.childCount; j++)
		{
			Transform child = trans.GetChild(j);
			CheckNotPerfectPixelLabel(objPath + "/" + child.name, child);
		}
	}
}
